import { sp } from 'cc';
import { Observable, Observer } from 'rxjs';

export function SkeletonPlay(skeleton: sp.Skeleton, animationName: string, loop = false): Observable<any> {
    return new Observable((observer: Observer<{ state: string, target: sp.Skeleton, event?: any }>) => {
        skeleton.setAnimation(0, animationName, loop);
        skeleton.setCompleteListener((trackEntry: any) => {
            // console.log('SkeletonPlay', 'complete', trackEntry);
            observer.next({ state: 'complete', target: skeleton });
            if (!loop) observer.complete();
        });
        skeleton.setEventListener((trackEntry: any, event: any) => {
            console.log('SkeletonPlay', 'event', trackEntry, event);
            observer.next({ state: 'event', target: skeleton, event });
        });
        return () => {
            // skeleton.clearTracks();
        }
    });
}

export function SkeletonPlayFromTo(skeleton: sp.Skeleton, animationName: string, from = 0, to = 1): Observable<{ state: string, target: sp.Skeleton, event: any }> {
    return new Observable((observer: Observer<{ state: string, target: sp.Skeleton, event: any }>) => {
        skeleton.timeScale = 0;
        let tr = skeleton.setAnimation(0, animationName, false);
        tr.animationStart = from * tr.animation.duration;
        tr.animationEnd = to * tr.animation.duration;
        skeleton.timeScale = 1;
        skeleton.setCompleteListener((trackEntry: any) => {
            // console.log('SkeletonPlay', 'complete', trackEntry);
            observer.next({ state: 'complete', target: skeleton, event: null });
            observer.complete();
        });
        skeleton.setEventListener((trackEntry: any, event: any) => {
            // console.log('SkeletonPlay', 'event', trackEntry, event);
            observer.next({ state: 'event', target: skeleton, event: event });
        });
        return () => {
            // skeleton.clearTracks();
        }
    });
}